import time
import os_tool as tool
import requests
import json
import pandas as pd
import re
from selenium import webdriver
from selenium.webdriver import ActionChains


def get_hero_info():
    url1 = 'https://pvp.qq.com/web201605/js/herolist.json'

    headers1 = {
        'cookie': 'PTTuserFirstTime=1733356800000; PTTosSysFirstTime=1733356800000; PTTosFirstTime=1733356800000; ts_refer=www.baidu.com/link; pgv_pvid=1897800623; ts_uid=4688530408; weekloop=0-0-0-49; eas_sid=Z1F76333t3R844P8w479l0O4u0; _qimei_uuid42=18c050f2f1e100916e9afbe0f99b097a02268fdb03; _qimei_fingerprint=1b62f5c2fee04bdd6a20f87f004f6a1f; _qimei_q36=; _qimei_h38=8f9570076e9afbe0f99b097a02000004118c05; lcad_o_minduid=fkVl6bxNf6sa6T7jMY2lPV6KBonrCFr0; lcad_appuser=3B19D1BEE868B385; ieg_ingame_userid=qSEHRZVrAKRZkKKfoSygxdKeCZGTOBMA; fqm_pvqid=2348b5fa-1a09-47eb-b4a4-3e2f89db43e0; fqm_sessionid=3977f8bf-7f59-4fca-a76d-71f292b4ba99; pgv_info=ssid=s1688419847; _qpsvr_localtk=0.2557651852016123; ptui_loginuin=1165872335; RK=o21dDSeTHS; ptcz=2ff12fc78d1fe6660a8f62f160eed1ac7b0556f3fdc605681e137808c4615fd3; uin=o1165872335; isHostDate=20063; isOsSysDate=20063; isOsDate=20063; eas_entry=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3D3enAW1WE1eEOXFPU0LXnNlpU56e4HSxWfOANYP1gd8u%26wd%3D%26eqid%3Dd0b4768e00625c02000000066752a9d3; lcad_LDERturn=707; ts_last=pvp.qq.com/web201605/herolist.shtml; pvpqqcomrouteLine=index_herolist_herolist; PTTDate=1733470722376',
        'referer': 'https://pvp.qq.com/web201605/herolist.shtml',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
    }

    hero_type_dict = {
        1:'战士',
        2:'法师',
        3:'坦克',
        4:'刺客',
        5:'射手',
        6:'辅助'
    }

    ename_list = []
    cname_list = []
    id_name_list = []
    title_list = []
    new_type_list = []
    hero_type_list = []
    hero_type2_list = []
    skin_name_list = []

    response1 = requests.get(url=url1, headers=headers1)
    response1.encoding = response1.apparent_encoding

    info = response1.text.replace("\t", "").replace("\r\n", "")
    info = '{"hero_list":' + info + '}'
    info = json.loads(info)

    hero_list = info['hero_list']
    for hero in hero_list:
        ename_list.append(hero['ename'])
        cname_list.append(hero['cname'])
        id_name_list.append(hero['id_name'])
        title_list.append(hero['title'])
        new_type_list.append(hero['new_type'])
        hero_type_list.append(hero_type_dict.get(hero['hero_type']))
        try:
            hero_type2_list.append(hero_type_dict.get(hero['hero_type2']))
        except:
            hero_type2_list.append('无')
        skin_name_list.append(hero['skin_name'])

    hero_dict = {
        '英雄编号': ename_list,
        '英雄名称': cname_list,
        '英雄英文名称': id_name_list,
        '英雄外号': title_list,
        '是否是新英雄': new_type_list,
        '英雄定位': hero_type_list,
        '英雄定位2': hero_type2_list,
        '皮肤名称': skin_name_list
    }

    pd.DataFrame(hero_dict).to_csv('./data/王者英雄基本信息.csv',index=False)
    return id_name_list

def get_one_hero_em(ids):
    # https://pvp.qq.com/web201605/herodetail/ying.shtml
    url1 = f'https://pvp.qq.com/web201605/herodetail/{ids}.shtml'
    diver = webdriver.Chrome()
    diver.maximize_window()
    diver.get(url1)

    # 定位到一个英雄的标签，进行迪点击，此时会产生新的页面
    # 需要跳转到新的页面
    windows = diver.window_handles
    # diver.switch_to_window(windows[1])
    diver.switch_to.window(windows[1])


    # 爬取
    diver.close()



    hero_id_url = str(diver.find_element_by_xpath('//div[@class="zk-con1 zk-con"]').get_attribute('style'))
    hero_id = re.findall(r'hero-info/(\d+)/', hero_id_url)[0]

    li_list = diver.find_elements_by_xpath('//ul[@class="cover-list"]/li')

    hero_em_dict = dict()

    for li in li_list:
        em_text = li.find_element_by_xpath('./em').text
        em_rant = li.find_element_by_xpath('./span/i').get_attribute('style')[7:-1]
        hero_em_dict[em_text] = em_rant

    # 获取英雄关系
    # 通过观察后发现，英雄关系数据，需要鼠标悬停后才能爬取对应的关系数据
    # 默认打开的界面是最佳搭档的数据
    # //div[@class="hero-info-box"]/div/div[1]
    div_zui_jia = diver.find_element_by_xpath('//div[@class="hero-info-box"]/div/div[1]')
    res_zui_jia = div_zui_jia.find_element_by_xpath('./div[@class="hero-f1 fl"]').text
    zui_jia_li_list = div_zui_jia.find_elements_by_xpath('./div[2]/ul/li')
    res_zui_jia_list = []
    for li in zui_jia_li_list:
        res_hero_id = re.findall(r'https://pvp.qq.com/web201605/herodetail/(\d+).shtml',str(li.find_element_by_xpath('./a').get_attribute('href')))[0]
        res_zui_jia_list.append(res_hero_id)
    hero_em_dict[res_zui_jia] = res_zui_jia_list

    # 压制英雄，需要鼠标悬停后再进行上面的爬取
    # //ul[@class="hero-hd"]/li[2]
    e = diver.find_element_by_xpath('//ul[@class="hero-hd"]/li[2]')
    ActionChains(diver).move_to_element(to_element=e).perform()
    div_ya_zhi = diver.find_element_by_xpath('//div[@class="hero-info-box"]/div/div[2]')
    res_ya_zhi = div_ya_zhi.find_element_by_xpath('./div[@class="hero-f1 fl"]').text
    ya_zhi_li_list = div_ya_zhi.find_elements_by_xpath('./div[2]/ul/li')
    res_ya_zhi_list = []
    for li in ya_zhi_li_list:
        res_hero_id = re.findall(r'https://pvp.qq.com/web201605/herodetail/(\d+).shtml',str(li.find_element_by_xpath('./a').get_attribute('href')))[0]
        res_ya_zhi_list.append(res_hero_id)
    hero_em_dict[res_ya_zhi] = res_ya_zhi_list

    # 被压制英雄，需要鼠标悬停后再进行上面的爬取
    # //ul[@class="hero-hd"]/li[2]
    e = diver.find_element_by_xpath('//ul[@class="hero-hd"]/li[3]')
    ActionChains(diver).move_to_element(to_element=e).perform()
    div_bei_ya_zhi = diver.find_element_by_xpath('//div[@class="hero-info-box"]/div/div[3]')
    res_bei_ya_zhi = div_bei_ya_zhi.find_element_by_xpath('./div[@class="hero-f1 fl"]').text
    ya_bei_zhi_li_list = div_bei_ya_zhi.find_elements_by_xpath('./div[2]/ul/li')
    res_bei_ya_zhi_list = []
    for li in ya_bei_zhi_li_list:
        res_hero_id = re.findall(r'https://pvp.qq.com/web201605/herodetail/(\d+).shtml',str(li.find_element_by_xpath('./a').get_attribute('href')))[0]
        res_bei_ya_zhi_list.append(res_hero_id)
    hero_em_dict[res_bei_ya_zhi] = res_bei_ya_zhi_list


    # 获取推荐出装
    e1 = diver.find_element_by_xpath('//ul[@class="equip-hd"]/li[1]')
    ActionChains(diver).move_to_element(to_element=e1).perform()
    # input("回车继续")
    frist_chu_zhuang_list = diver.find_element_by_xpath('//div[@class="equip-bd"]/div[1]/ul').get_attribute('data-item')
    hero_em_dict['推荐出装一'] = frist_chu_zhuang_list

    e1 = diver.find_element_by_xpath('//ul[@class="equip-hd"]/li[2]')
    ActionChains(diver).move_to_element(to_element=e1).perform()
    # input("回车继续")
    second_chu_zhuang_list = diver.find_element_by_xpath('//div[@class="equip-bd"]/div[2]/ul').get_attribute('data-item')
    hero_em_dict['推荐出装二'] = second_chu_zhuang_list


    diver.quit()
    return  hero_id,hero_em_dict

if __name__ == '__main__':
        tool.kill_process('chromedriver.exe')

        id_name_list = get_hero_info()
        hero_id_list = [] # 英雄编号
        viability_list = [] # 生存能力
        attack_damage_list = [] # 攻击伤害
        skill_effect_list = [] # 技能效果
        hands_difficulty_list = [] # 上手难度
        partner_list = [] # 最佳搭档
        suppressing_heroes_list = [] # 压制英雄
        suppressed_heroes_list = [] # 被压制英雄
        zhuangbei_hero_list1 = []
        zhuangbei_hero_list2 = []


        for id_name in id_name_list:
            hero_hid,em_dict = get_one_hero_em(id_name)
            hero_id_list.append(hero_hid)
            viability_list.append(em_dict.get('生存能力'))
            attack_damage_list.append(em_dict.get('攻击伤害'))
            skill_effect_list.append(em_dict.get('技能效果'))
            hands_difficulty_list.append(em_dict.get('上手难度'))
            partner_list.append(','.join(em_dict.get('最佳搭档')))
            print(hero_hid, em_dict)
            # print(em_dict.get('压制英雄'), type(em_dict.get('压制英雄')))
            suppressing_heroes_list.append(','.join(em_dict.get('压制英雄')))
            suppressed_heroes_list.append(','.join(em_dict.get('被压制英雄')))
            zhuangbei_hero_list1.append(em_dict.get('推荐出装一'))
            zhuangbei_hero_list2.append(em_dict.get('推荐出装二'))

        hero_detailed_info = {
            '英雄编号':hero_id_list,
            '生存能力': viability_list,
            '攻击伤害': attack_damage_list,
            '技能效果': skill_effect_list,
            '上手难度': hands_difficulty_list,
            '最佳搭档': partner_list,
            '压制英雄': suppressing_heroes_list,
            '被压制英雄': suppressed_heroes_list,
            '推荐出装一': zhuangbei_hero_list1,
            '推荐出装二': zhuangbei_hero_list2
        }

        pd.DataFrame(hero_detailed_info).to_csv('data/王者荣耀英雄详细信息.csv',index=False)